/*******************************************************************************
* CSCI321 Major Project 2010 - University of Wollongong                        *
********************************************************************************
* Program:		WeaveEdit                                              *
* Authors:		Simon Allen (Student#: 3457527, Unix: sa655)           *
*			Scott Bellis (Student#: 3479110, Unix: sjb900)         *
*			Jason Benger (Student#: 3454137, Unix: jb960)          *
*			Timothy Newmarch (Student#: 3459263 Unix: tgn336)      *
*			Benjamin Richardson (Student# 3467752, Unix: bjr401)   *
* Supervisor:		Daniel F. Saffioti                                     *
* Modified:		28/10/2010                                             *
* Description:		WeaveEdit is a highly portable collaborative text      *
*			editor and word processor, allowing several users to   *
*			read and edit multiple documents at the same time.     *
*			It is available for Mac OS X, Windows and Linux,       *
*			utilising Nokia's Qt development framework.            *
*******************************************************************************/


#include "htmlindenter.h"
#include "Editor/texteditor.h"


/**
  * Indent a line using custom automatic indentation rules defined below.
  */
void HTMLIndenter::indent()
{
	QTextCursor cursor = editor->textCursor();
	int numTabs = 0, newLinePos = cursor.position() - 2;
	bool newLevel = false;
	int startOfTag = 0;

	// Go back till we find the first non-space character.
	while (newLinePos >= 0 && editor->document()->characterAt(newLinePos).isSpace())
		newLinePos--;

	if (editor->document()->characterAt(newLinePos) == Qt::Key_Greater)
	{
		startOfTag = newLinePos;

		// Go back till we find the start of the tag or start of file.
		while (startOfTag >= 0 && editor->document()->characterAt(startOfTag) != Qt::Key_Less)
			startOfTag--;

		// The first characters we found was a <...> tag, so new level of indentation.
		if (startOfTag >= 0 && editor->document()->characterAt(startOfTag) == Qt::Key_Less
		    && editor->document()->characterAt(startOfTag + 1) != Qt::Key_Slash)
		{
			numTabs = 1; // Increase the indent.
			newLevel = true;
		}
	}

	// Go back from the previous block until we hit a new line/start.
	for (; newLinePos >= 0 && editor->document()->characterAt(newLinePos).toAscii() != '\0'; newLinePos--)
		;

	// Now count the number of tabs until that block starts.
	for (newLinePos++; editor->document()->characterAt(newLinePos) == '\t'; newLinePos++)
		numTabs++;

	// There is some form of indentation, isnert it.
	if (numTabs > 0)
		editor->insertPlainText(QString(numTabs, '\t'));

	editor->setTextCursor(cursor);
}
